<template>
  <div>
    <h1>商品管理</h1>
    <button class="btn-primary" @click="goToAddProduct">添加商品</button>

    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>名称</th>
          <th>价格</th>
          <th>图片</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="product in productList" :key="product.id">
          <td>{{ product.id }}</td>
          <td>{{ product.name }}</td>
          <td>{{ product.price }}</td>
          <td><img :src="product.image" alt="Product Image" width="50" height="50"></td>
          <td>
            <button type="button" class="btn-danger" @click="deleteProduct(product.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      productList: []
    };
  },
  mounted() {
    this.fetchProductList();
  },
  methods: {
    fetchProductList() {
      this.$http
        .get('/goods/goodslist')
        .then((response) => {
          this.productList = response.data.data;
        })
        .catch((error) => {
          console.error('获取商品列表失败:', error);
        });
    },
    deleteProduct(productId) {
      this.$http
        .delete('/goods/deletegoods', { data: { id: productId } })
        .then((response) => {
          if (response.data.code === 1) {
            this.fetchProductList();
          }
        })
        .catch((error) => {
          console.error('删除商品失败:', error);
        });
    },
    goToAddProduct() {
      // 跳转到添加商品页面
      this.$router.push('/admin/goods_info');
    }
  }
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.img-container {
  width: 50px;
  height: 50px;
}

.btn-primary {
  background-color: #007bff;
  color: white;
  padding: 5px 10px;
  margin-right: 5px;
  cursor: pointer;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
  padding: 5px 10px;
  cursor: pointer;
}
</style>
